package controllers;

import play.*;
import play.mvc.*;
import play.data.validation.*;

import java.util.*;

import models.*;

import notifiers.*;

import play.libs.Mail;

@With(Secure.class)
public class AppointmentCreation extends Controller {

    public static void invite(@Required(message = "Bitte wähle ein Datum") String _date, @Required(message = "Bitte Zeit wählen")String _time, @Required(message = "Bitte ein Restaurant wählen")String restaurantchoice) {
		
		// validation.required(_date);
		// 		validation.required(_time);
		// 		validation.required(restaurantchoice);
		
		if(validation.hasErrors()) {
		          params.flash(); // add http parameters to the flash scope
		          validation.keep(); // keep the errors for the next request
		          Application.index();
		}
		
		Customer custom = Customer.findByEmail(Security.connected());
	
		System.out.println("#######");
		System.out.println(restaurantchoice);
		System.out.println(_date);
		System.out.println(_time);
		Restaurant rest = Restaurant.find("byName", restaurantchoice).first();
		Appointment app = new Appointment(custom, _date, "Keine Nachricht", rest, _time);
		app.save();
		List<Person> friendsList = custom.friends;

		render(friendsList, app);
    	
    }

	

	public static void confirm(@Required Long appid, String[] friend_list,
			String[] person_fname, String[] person_lname, String[] person_email, String personal_message) {
				
		for (String str : person_email) {
			if(str != null && str.length() != 0) {
				validation.email(str);
			}
		}
		
		//TODO
		// if(validation.hasErrors()) {
		// 		          params.flash(); // add http parameters to the flash scope
		// 		          validation.keep(); // keep the errors for the next request
		// 							Appointment app = Appointment.findById(appid);
		// 							Customer custom = Customer.findByEmail(Security.connected());
		// 							List<Person> friendsList = custom.friends;
		// 		          AppointmentCreation.invite(app.date, app.time, app.restaurant.name);
		// 		}
		
		
		
		List<Person> invitees = new ArrayList<Person>();
		Customer custom = Customer.findByEmail(Security.connected());
		
		if (friend_list != null) {
			for (String email : friend_list) {
				Person tmp_person = Person.find("byEmail", email).first();
				invitees.add(tmp_person);
			}
		}
		
		for (int i = 0; i < person_email.length; i++) {
			if (validation.email(person_email[i]).ok && !person_email[i].isEmpty() 
					&& !person_fname[i].isEmpty() && !person_lname[i].isEmpty()) {
				Person new_person = Person.find("byEmail", person_email[i]).first(); 
				if ( new_person == null) {
					new_person = new Person(person_fname[i], person_lname[i], person_email[i]);
					new_person.save();
					custom.friends.add(new_person);
					custom.save();
				} else {
					if (!custom.friends.contains(new_person)) {
						custom.friends.add(new_person);
					}
				}
				invitees.add(new_person);
			}
		}
		
		Appointment app = Appointment.findById(appid);
		if(personal_message != null && personal_message.length() != 0) {
			app.comment = personal_message;
			app.save(); 
		}
		// Create an invite for the owner
		Invite owner_inv = new Invite(custom.person, app);
		owner_inv.save();
		for (Person person : invitees) {
			Invite inv = new Invite(person, app);
			inv.save();
		}
		render(app, invitees);

	}
	
	public static void done(Long appId, String restaurant_message) {
		
		Appointment appointment = Appointment.findById(appId);
		appointment.state = Appointment.STATE_COMPLETE;
		List<Invite> invites = Invite.find("byAppointment", appointment).fetch();
		for (Invite invite : invites) {
			if (invite.invitee != appointment.owner.person)
				Mails.invitation(invite);
		}
		appointment.save();
		
		Invite owner_inv = Invite.find("byAppointmentAndInvitee",
					appointment, appointment.owner.person).first();
		render(appointment, owner_inv);
	}
	
	
	public static void overview() {
		Customer custom = Customer.findByEmail(Security.connected());
		List<Appointment> appIncomplete = Appointment.find("byOwnerAndState", custom, Appointment.STATE_INCOMPLETE).fetch();
		List<Appointment> appComplete = Appointment.find("byOwnerAndState", custom, Appointment.STATE_COMPLETE).fetch();
		List<Appointment> appFrozen = Appointment.find("byOwnerAndState", custom, Appointment.STATE_FROZEN).fetch();
		
		// Liste<Invite> invites = Invite.find(appointment);
		
		render(appIncomplete, appComplete, appFrozen, custom);
	}
	
	public static void overviewDetail(Long appId) {
		Appointment appointment = Appointment.findById(appId);
		List<Invite> invites = Invite.find("byAppointment", appointment).fetch();
		
		List<Meal> orderedMeals = new LinkedList<Meal>();
		//List<MealOrder> mealOrders = Meal.find("SELECT mo FROM MealOrder mo WHERE mo.invite.appointment = ?", appointment).fetch();
		//List<MealOrder> mealOrders = Meal.find("SELECT mo FROM MealOrder mo WHERE mo.invite IN (?)", invites.toArray()).fetch();
		
		//for(MealOrder mo : mealOrders) {
		//	orderedMeals.addAll( mo.meals );
		//}
		
		render(appointment, invites, orderedMeals);
	}
	
	public static void setFrozen(Long appId) {
			Appointment appointment = Appointment.findById(appId);
			appointment.state = Appointment.STATE_FROZEN;
			appointment.save();
			
			AppointmentCreation.overview();
	}
	
	
	public static void addToFavorite(Long restId) {
		Restaurant rest = Restaurant.findById(restId);
		Customer custom = Customer.findByEmail(Security.connected());
		
		Favorite fav = new Favorite(custom, rest);	
		fav.save();
		
		Application.index();
	}
	
	public static void delete(Long appId) {
		Appointment appointment = Appointment.findById(appId);
		appointment.state = "DELETED";
		appointment.save();
		
		AppointmentCreation.overview();
	}
   
}